<template>
  <div class="app-container">
    <el-form class="alone-business" :model="queryData" ref="queryDataRef" :inline="true" label-width="68px">
      <el-form-item label="代理商">
        <el-input v-model="queryData.agentKey" placeholder="请输入姓名或者手机号" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="所在城市">
        <el-cascader
          v-model="queryData.regionIdListId"
          :options="queryAreaOptions"
          :props="areaProps"
          placeholder="请选择"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="业务员">
        <el-select-v2
          v-model="queryData.introducerTenantId"
          filterable
          remote
          :remote-method="selectIntroducerTenantRemoteMethod"
          :options="selectIntroducerTenantOptions"
          :props="introducerTenantProps"
          :loading="selectLoading"
          placeholder="请选择"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="加盟商">
        <div class="numrange">
          <el-input-number :min="0" :max="2000000000" v-model="queryData.franchiseeCountMin" :controls="false" />
          <span> - </span>
          <el-input-number :min="0" :max="2000000000" v-model="queryData.franchiseeCountMax" :controls="false" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="searchData">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button type="primary" plain icon="Plus" @click="openMarketing('')">添加代理商</el-button>
    </el-row>
    <el-table
      ref="tableRef"
      v-loading="tableLoading"
      :data="tableData"
      highlight-current-row
      @sort-change="sortChange"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column property="agentName" label="代理商名称" width="180" />
      <el-table-column property="phoneNumber" label="联系方式" width="120" />
      <el-table-column property="area" label="所在城市" />
      <el-table-column property="introducerTenantName" label="业务员" width="120" />
      <el-table-column property="franchiseeCount" label="开拓加盟商数" sortable="custom" width="130" />
      <el-table-column property="franchiseeOrderCount" label="加盟商订单数" sortable="custom" width="130" />
      <el-table-column property="status" label="状态" width="120">
        <template #default="scope">
          <el-switch v-model="scope.row.status" disabled style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe6" />
        </template>
      </el-table-column>
      <el-table-column property="joinTime" label="入驻日期" width="120" />
      <el-table-column fixed="right" label="操作" width="100">
        <template #default="scope">
          <el-button link type="primary" @click="openMarketing(scope.row)"> 编辑 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="listTotal" v-model:page="queryData.current" v-model:limit="queryData.size" @pagination="getTable" />

    <!-- 添加/编辑代理商 抽屉 -->
    <el-drawer
      title="添加代理商"
      v-model="channelDrawer"
      @close="closeChannel(channelFormRef)"
      size="600px"
      append-to-body
      class="rebate-rules-drawer"
    >
      <div class="spase">
        <el-scrollbar max-height="calc(100vh - 90px)">
          <!-- 查看编辑 显示 -->
          <template v-if="channelForm.agentTenantId">
            <!-- <el-row class="info-tips" justify="space-between">
                <div>会员信息：</div>
              </el-row> -->
            <div class="info-drawer" v-if="channelForm.orgType == 2">
              <img class="img-icon" alt="" src="@/assets/images/products/personal_icon.png" />
              <div class="info-item">
                <el-row style="margin-bottom: 10px">
                  <div class="label">姓名</div>
                  <div class="text">{{ channelForm.personName }}</div>
                </el-row>
                <el-row>
                  <div class="label">手机号</div>
                  <div class="text">{{ channelForm.personCode }}</div>
                </el-row>
              </div>
            </div>
            <div class="info-drawer" v-if="channelForm.orgType == 1">
              <el-row justify="space-between">
                <img class="img-icon" alt="" src="@/assets/images/products/mechanism_icon.png" />
                <div class="img-text">如果是“机构”身份，后续绑定对公账户，佣金将发放到公账户</div>
              </el-row>
              <div class="info-item">
                <el-row style="margin-bottom: 10px">
                  <div class="label">机构名称</div>
                  <div class="text">{{ channelForm.orgName }}</div>
                </el-row>
                <el-row style="margin-bottom: 10px">
                  <div class="label">信用代码</div>
                  <div class="text">{{ channelForm.socialCodeId }}</div>
                </el-row>
                <el-row>
                  <div class="label">管理员手机号</div>
                  <div class="text">{{ channelForm.account }}</div>
                </el-row>
              </div>
            </div>
          </template>
          <el-form
            style="width: 100%"
            ref="channelFormRef"
            :model="channelForm"
            :rules="channelRules"
            label-position="top"
            label-width="80px"
          >
            <!-- 新增 显示 -->
            <template v-if="!channelForm.agentTenantId">
              <el-form-item prop="orgType">
                <el-radio-group v-model="channelForm.orgType">
                  <el-radio :value="2">个人</el-radio>
                  <el-radio :value="1">机构</el-radio>
                </el-radio-group>
              </el-form-item>
              <template v-if="channelForm.orgType == 2">
                <el-form-item label="姓名" prop="personName">
                  <el-input v-model="channelForm.personName" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="手机号" prop="personCode">
                  <el-input v-model="channelForm.personCode" placeholder="请输入手机号" maxlength="11" />
                </el-form-item>
              </template>
              <template v-if="channelForm.orgType == 1">
                <el-form-item label="机构名称" prop="orgName">
                  <el-input v-model="channelForm.orgName" placeholder="请输入机构名称" />
                </el-form-item>
                <el-form-item label="营业执照编码" prop="socialCodeId">
                  <el-input v-model="channelForm.socialCodeId" placeholder="请输入营业执照编码" />
                </el-form-item>
                <el-form-item label="管理员手机号" prop="account">
                  <el-input v-model="channelForm.account" placeholder="请输入" maxlength="11" />
                </el-form-item>
              </template>
            </template>

            <el-form-item label="家装通开拓人员" :rules="[{ required: true }]" for="XX">
              <div class="form-item-wrap">
                <el-switch
                  v-model="channelForm.hasIntroducer"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #dcdfe6"
                  :disabled="!isChannelEdit"
                  @change="switchChange"
                />
                <el-form-item class="select-v2" v-if="channelForm.hasIntroducer" prop="introducerTenantId">
                  <el-select-v2
                    v-model="channelForm.introducerTenantId"
                    filterable
                    remote
                    :remote-method="introducerTenantRemoteMethod"
                    :options="introducerTenantOptions"
                    :props="introducerTenantProps"
                    :loading="selectLoading"
                    placeholder="请选择"
                    :disabled="!isChannelEdit"
                /></el-form-item>
              </div>
            </el-form-item>
            <el-form-item label="所在城市" prop="areaId">
              <el-cascader
                v-model="channelForm.areaId"
                :options="areaOptions"
                :props="areaProps"
                filterable
                :disabled="!isChannelEdit"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="备注说明" prop="remark">
              <el-input
                v-model="channelForm.remark"
                style="width: 100%"
                :rows="2"
                type="textarea"
                placeholder="请输入"
                :disabled="!isChannelEdit"
              />
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>

      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeChannel(channelFormRef)">取 消</el-button>
          <el-button
            class="btn"
            v-if="isChannelEdit"
            :loading="marketingBtn"
            type="primary"
            @click="submitChannel(channelFormRef)"
            >确 定</el-button
          >
          <el-button class="btn" v-else type="primary" @click="isChannelEdit = true">编 辑</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
import { getArea } from "@/api/tenant";
import { agencyPage, addAgency, agencyDetail, edit, supplyChainList } from "@/api/agencyModel/agentManagement";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();

// 搜索条件
const queryData = ref({});

// 商家表格总数
const listTotal = ref(0);

// 查询
const searchData = () => {
  if (queryData.value.regionIdListId?.length > 0) {
    queryData.value.regionId = queryData.value.regionIdListId[1];
  }
  getTable();
};

// 搜索重置
const reset = () => {
  queryData.value = {
    agentKey: "",
    regionIdListId: "",
    regionId: "",
    introducerTenantId: "",
    franchiseeCountMin: "",
    franchiseeCountMax: "",
    current: 1,
    size: 10
  };
  getTable();
  tableRef.value.clearSort();
};

// 表格数据
const tableData = ref([]);
const tableLoading = ref(false);
const tableRef = ref();

const channelDrawer = ref(false);
const channelForm = ref({});
const channelRules = {
  personName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  personCode: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号输入错误", trigger: "blur" }
  ],
  orgName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  socialCodeId: [{ required: true, message: "请输入营业执照编码", trigger: "blur" }],
  account: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号输入错误", trigger: "blur" }
  ],
  areaId: [{ required: true, message: "请选择代理商所在城市", trigger: "change" }],
  hasIntroducer: [{ required: true, message: "请选择开拓人员", trigger: "change" }],
  introducerTenantId: [{ required: true, message: "请选择开拓人员", trigger: "change" }]
};
// 搜索条件-无区
const queryAreaOptions = ref([]);
// 抽屉-所在城市
const areaOptions = ref([]);
const areaProps = {
  value: "id",
  label: "name"
};
const channelFormRef = ref();
const marketingBtn = ref(false);
// 是否可编辑
const isChannelEdit = ref(true);

// 是否点击过表格操作按钮编辑
const editStart = ref(false);
// 打开营销返佣抽屉
const openMarketing = row => {
  channelForm.value = {
    orgType: 2
  };
  channelDrawer.value = true;
  isChannelEdit.value = true;
  editStart.value = false;
  //   getAreaApi();
  if (row) {
    channelForm.value = {};
    agencyDetail(row.agentTenantId).then(res => {
      console.log(res);
      channelForm.value = res.data;
      introducerTenantRemoteMethod(res.data.introducerTenantName);
    });
    isChannelEdit.value = false;
    editStart.value = true;
  }
};
// 关闭营销抽屉
const closeChannel = formRef => {
  if (!formRef) return;
  channelDrawer.value = false;
  channelForm.value = {};
  marketingBtn.value = false;
  formRef.resetFields();
};
// 提交营销设置
const submitChannel = formRef => {
  if (!formRef) return;
  formRef.validate((valid, fields) => {
    if (valid) {
      channelForm.value.hasIntroducer = channelForm.value.hasIntroducer ? channelForm.value.hasIntroducer : false;
      if (channelForm.value.hasIntroducer) {
        channelForm.value.introducerTenantName = introducerTenantOptions.value.find(item => {
          return item.introducerTenantId == channelForm.value.introducerTenantId;
        })?.introducerName;
      }
      let postData = { ...channelForm.value };
      marketingBtn.value = true;
      if (!editStart.value) {
        postData.areaId = postData.areaId[2];
        addAgency(postData)
          .then(res => {
            ElMessage.success("添加成功");
            closeChannel(channelFormRef.value);
            getTable();
          })
          .catch(err => {
            marketingBtn.value = false;
          });
      } else {
        if (postData.areaId instanceof Array) {
          postData.areaId = postData.areaId[2];
        }
        edit(postData)
          .then(res => {
            ElMessage.success("编辑成功");
            closeChannel(channelFormRef.value);
            getTable();
          })
          .catch(err => {
            marketingBtn.value = false;
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 抽屉表单-开关变化
const switchChange = val => {
  if (val == 0) {
    channelForm.value.introducerTenantId = "";
    channelForm.value.introducerTenantName = "";
  }
};

const introducerTenantOptions = ref([]);
const introducerTenantProps = {
  label: "title",
  value: "introducerTenantId"
};
const selectLoading = ref(false);
// 家装通开拓人员-下拉列表查询
const introducerTenantRemoteMethod = query => {
  if (query !== "") {
    selectLoading.value = true;
    supplyChainList({ key: query }).then(res => {
      selectLoading.value = false;
      introducerTenantOptions.value = res.data;
    });
  } else {
    introducerTenantOptions.value = [];
  }
};

// 搜索条件-业务员-下拉列表查询
const selectIntroducerTenantOptions = ref([]);
const selectIntroducerTenantRemoteMethod = query => {
  if (query !== "") {
    selectLoading.value = true;
    supplyChainList({ key: query }).then(res => {
      selectLoading.value = false;
      selectIntroducerTenantOptions.value = res.data;
    });
  } else {
    selectIntroducerTenantOptions.value = [];
  }
};

// 获取地址
const getAreaApi = () => {
  getArea().then(res => {
    areaOptions.value = res.data;
    queryAreaOptions.value = JSON.parse(JSON.stringify(res.data));
    queryAreaOptions.value.forEach(item => {
      item?.children?.forEach(el => {
        el.children = [];
      });
    });
  });
};

// 排序变化
const sortChange = data => {
  if (!data.order) {
    delete queryData.value.orderByColumn;
    delete queryData.value.isAsc;
  } else {
    queryData.value.isAsc = data.order == "descending" ? "desc" : "asc";
    queryData.value.orderByColumn = data.prop;
  }
  getTable();
};

// 获取列表数据
const getTable = () => {
  tableLoading.value = true;
  agencyPage(queryData.value).then(res => {
    tableData.value = res.data.list;
    listTotal.value = res.data.total;
    tableLoading.value = false;
  });
};

onMounted(() => {
  getAreaApi();
  getTable();
});
</script>
<style lang="scss" scoped>
.alone-business {
  .numrange {
    width: 200px;
    display: flex;
    justify-content: space-between;

    span {
      width: 30px;
      text-align: center;
    }
  }
}
.info-tips {
  font-size: 14px;
  color: #86909c;
  margin-bottom: 20px;
}
.form-tips {
  margin-bottom: 20px;
  font-size: 14px;
  color: #ea0000;
}
.rebate-rules-drawer {
  .info-drawer {
    .img-icon {
      display: block;
      width: 84px;
      height: 24px;
    }
    .img-text {
      font-size: 12px;
      color: #86909c;
      line-height: 24px;
    }
    .info-item {
      // width: 435px;
      width: 100%;
      border-radius: 0px 4px 4px 4px;
      border: 1px solid #e5e8ef;
      padding: 10px 15px;
      margin-bottom: 20px;
      .label {
        font-size: 14px;
        color: #86909c;
        width: 100px;
      }
      .text {
        font-size: 14px;
        color: #3d3d3d;
      }
    }
  }
  .form-item-wrap {
    display: flex;
    flex-direction: row;
    width: 100%;
    .select-v2 {
      margin-left: 20px;
      flex: 1;
    }
  }

  .btn {
    width: 120px;
    height: 36px;
    line-height: 36px;
  }
}
</style>
<style lang="scss">
.rebate-rules-drawer {
  .el-drawer__header {
    margin-bottom: 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #dcdfe6;
  }
}
</style>
